package com.itheima.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author 王加鑫
 * @Date 2021/7/23 14:27
 * @Since JDK 1.9
 */
@Component
@Aspect
public class MyAdvice {
    //设置切入点，要求配置在方法上方
//    @Pointcut("execution(* com.itheima.dao.AnimalDao.*(..))")
//    public void ptAnimal(){}

    @Pointcut("execution(* com.itheima.service.StudentService.*(..))")
    public void ptStuService(){}

//    @Pointcut("execution(* com.itheima.dao.StudentDao.*(..))")
//    public void ptStuDao(){}

//    @Around("ptAnimal()")
//    public Object animalDao(ProceedingJoinPoint pjp) throws Throwable {
//        long startTime = System.currentTimeMillis();
//        Object ret = pjp.proceed();
//        long endTime = System.currentTimeMillis();
//        System.out.println("消耗时间：" + (endTime - startTime) + "毫秒");
//        return ret;
//    }

    @Around("ptStuService()")
    public Object stuSerAround(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        String declaringTypeName = signature.getDeclaringTypeName();
        String name = signature.getName();
        // 获取执行的签名对象
        long start = System.currentTimeMillis();
        for (int i = 0; i <10000 ; i++) {
            Object ret = pjp.proceed();
        }
        System.out.println(declaringTypeName + "." +name + "耗时：" + (System.currentTimeMillis() - start) + "ms");
        return null;
    }

/*    @Before("ptStuService()")
    public void stuSerBefore(JoinPoint jp){
        Object[] args = jp.getArgs();
        System.out.println(Arrays.toString(args));
        System.out.println("before advice ...");
    }*/

    @Around("ptStuService()")
    public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {

        Object[] args = pjp.getArgs();

        for (int i = 0; i < args.length; i++) {
            /*
            如果参数是String类型时，将String前后的空格去除掉
             */
            if(args[i].getClass().equals(String.class)){
                args[i] = args[i].toString().trim();
                System.out.println(args[i]);
            }
        }
        return pjp.proceed(args);
    }




}
